package com.uplift.mobile.realty.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.uplift.common.Const;
import com.uplift.common.base.BusinessException;
import com.uplift.common.base.ServiceReslut;
import com.uplift.common.utils.Excel2PDF;
import com.uplift.common.utils.ExcelOperationUtil;
import com.uplift.common.utils.UUIDGenerater;
import com.uplift.mobile.rate.service.IRateService;
import com.uplift.mobile.realty.dao.RealtyEarningsMapper;
import com.uplift.mobile.realty.dao.RealtyInfoMapper;
import com.uplift.mobile.realty.dao.RealtyLeaseMapper;
import com.uplift.mobile.realty.model.RealtyEarnings;
import com.uplift.mobile.realty.model.RealtyErModel;
import com.uplift.mobile.realty.model.RealtyInfo;
import com.uplift.mobile.realty.service.IRealtyEarningsService;
import com.uplift.mobile.user.dao.UserMapper;
import com.uplift.mobile.user.model.Receipts;
import com.uplift.mobile.user.model.User;
import com.uplift.mobile.user.service.IReceiptsService;
import com.uplift.sec.SecurityContext;

@Service
@Transactional
public class RealtyEarningsServiceImpl implements IRealtyEarningsService {

	@Autowired
	private RealtyEarningsMapper realtyEarningsMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RealtyLeaseMapper realtyLeaseMapper;
	@Autowired
	private RealtyInfoMapper realtyInfoMapper;
	@Autowired
	private IReceiptsService iReceiptsService;

	@Autowired
	private IRateService rateService;

	@Override
	public List<Map<String, Object>> queryRealtyEarnings(RealtyEarnings realtyEarnings) {
		PageHelper.startPage(realtyEarnings.getPage(), realtyEarnings.getLimit());
		return this.realtyEarningsMapper.selectRealtyEarnings(realtyEarnings);
	}

	@Override
	public ServiceReslut addRealtyEarnings(RealtyEarnings realtyEarnings) {

//		Map<String, Object> sessionUser = SecurityContext.getSessionUser();
//		if(sessionUser == null) {
//			return ServiceReslut.newServiceReslut(0, "获取登录用户信息失败");
//		}
//
//		realtyEarnings.setCreateUserId((String) sessionUser.get("id"));

		realtyEarnings.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		realtyEarnings.setState("1");
		realtyEarnings.setCreateTime(new Date());
		return ServiceReslut.newServiceReslut(realtyEarningsMapper.insertRealtyEarnings(realtyEarnings), "");
	}

	@Override
	public ServiceReslut updateRealtyEarnings(RealtyEarnings realtyEarnings) {
		realtyEarnings.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(realtyEarningsMapper.updateRealtyEarnings(realtyEarnings), "");
	}

	@Override
	public ServiceReslut deleteRealtyEarnings(RealtyEarnings realtyEarnings) {
		realtyEarnings.setState("0");		//删除状态
		realtyEarnings.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(realtyEarningsMapper.updateRealtyEarnings(realtyEarnings),"");
	}

	@Override
	public Map<String, Object> countEveMonthEarnings(RealtyEarnings realtyEarnings) {
		Map<String, Object> data = new HashMap<>();
		data.put("totalMoney", 0);
		data.put("totalJMoney", 0);
		data.put("everyMonth", new ArrayList<>());

		if(realtyEarnings == null) {
			return data;
		}

		if(StringUtils.isBlank(SecurityContext.getUserId())) {
			return data;
		}

		realtyEarnings.setCustomerId(SecurityContext.getUserId());
		if(StringUtils.isBlank(realtyEarnings.getAccountDate())) {
			return data;
		}

		BigDecimal rate = getRate(realtyEarnings);
		if(rate == null) {
			return data;
		}

		Map<String, Object> yearData = this.realtyEarningsMapper.countYearEarnings(realtyEarnings);
		if(yearData == null) {

			return data;
		}

		data.put("totalMoney", new BigDecimal(yearData.get("jsr")==null?"0":yearData.get("jsr").toString()).setScale(2,BigDecimal.ROUND_HALF_DOWN));
		data.put("totalJMoney", new BigDecimal(yearData.get("Jjsr")==null?"0":yearData.get("Jjsr").toString()).setScale(2,BigDecimal.ROUND_HALF_DOWN));

		if(StringUtils.isNotBlank(realtyEarnings.getRoomId()) && StringUtils.isBlank(realtyEarnings.getRealtyId())) {
			data.put("everyMonth", this.realtyEarningsMapper.countEveMonthEarnings(realtyEarnings));
		} else {
			List<Map<String, Object>> everyData = new ArrayList<>() ;
			List<Map<String, Object>> maps = this.realtyEarningsMapper.countEveMonthEarnings(realtyEarnings);

			List<Map<String, Object>> roomsData = null;
			for (Map<String, Object> map : maps) {
				RealtyErModel realtyErModel = new RealtyErModel();
				realtyErModel.setReId((String) map.get("id"));
				realtyErModel.setRate(rate);
				roomsData = this.realtyEarningsMapper.selectRoomsEarnings(realtyErModel);

				map.put("rooms", roomsData);
				everyData.add(map);
			}
			data.put("everyMonth", everyData);
		}

		return data;
	}

	@Override
	public Map<String, BigDecimal> countCustomerAsset(RealtyEarnings realtyEarnings) throws Exception {
		if(realtyEarnings == null) {
			realtyEarnings = new RealtyEarnings();
		}

		//默认返回内容
		Map<String, BigDecimal> data = new HashMap<>();
		data.put("totalBuyPrice", new BigDecimal("0"));
		data.put("totalBuyJPrice", new BigDecimal("0"));
		data.put("totalMoney", new BigDecimal("0"));
		data.put("totalJMoney", new BigDecimal("0"));
		data.put("totalZZC", new BigDecimal("0"));
		data.put("totalJZZC", new BigDecimal("0"));
		data.put("totalReceipts", new BigDecimal("0"));
		data.put("totalJReceipts", new BigDecimal("0"));
		data.put("balance", new BigDecimal("0"));
		data.put("Jbalance", new BigDecimal("0"));

		if(StringUtils.isBlank(realtyEarnings.getAccountDate())) {      //如果没有传年份，则默认为当前年份
			Calendar now = Calendar.getInstance();
			String year = now.get(Calendar.YEAR)+"";
			realtyEarnings.setAccountDate(year);
		}
//      原来
		realtyEarnings.setCustomerId(SecurityContext.getUserId());



		BigDecimal rate = getRate(realtyEarnings);          //查询汇率
		if(rate == null) {
			return data;
		}

		setBuyPrice(data, realtyEarnings);              //设置客户总资产
		setCustomerTotalMoney(data, realtyEarnings);    //设置客户累计现金流
		setCustomerZZC(data, realtyEarnings);           //设置客户总支出
		//znl修改
		setCustomerZZCByZnl(data, realtyEarnings);      //累计年的设置客户总支出
		setCustomerReceipts(data, realtyEarnings);      //设置客户汇款额
//
//		data.put("balance", data.get("totalMoney").subtract(data.get("totalZZC")).subtract(data.get("totalReceipts").setScale(2,BigDecimal.ROUND_HALF_UP)));
//		data.put("Jbalance", data.get("totalJMoney").subtract(data.get("totalJZZC")).subtract(data.get("totalJReceipts").setScale(2,BigDecimal.ROUND_HALF_UP)));
		//znl 改
		data.put("balance", data.get("totalMoney").subtract(data.get("totalZZCForZnl")).subtract(data.get("totalReceipts").setScale(2,BigDecimal.ROUND_HALF_UP)));
		data.put("Jbalance", data.get("totalJMoney").subtract(data.get("totalJZZCForZnl")).subtract(data.get("totalJReceipts").setScale(2,BigDecimal.ROUND_HALF_UP)));
		return data;
	}

	@Override
	public String exportDetail(RealtyEarnings realtyEarnings) throws Exception {

		RealtyInfo realtyInfo = new RealtyInfo();
		realtyInfo.setCustomerId(SecurityContext.getUserId());
		List<Map<String, Object>> realtys = realtyInfoMapper.selectRealtyInfo(realtyInfo);
		if(CollectionUtils.isEmpty(realtys)) {
			throw new BusinessException("导出失败，查询物业信息失败");
		}

		if(StringUtils.isBlank(realtyEarnings.getExportType())) {
			throw new BusinessException("导出失败，导出类型不能为空");
		}
		if(StringUtils.isBlank(realtyEarnings.getExportVaule())) {
			throw new BusinessException("导出失败，时间不能为空");
		}

		ArrayList dates = createDates(realtyEarnings);
		if(CollectionUtils.isEmpty(dates)) {
			throw new BusinessException("导出失败，时间不能为空");
		}

		User user = new User();
		user.setId(SecurityContext.getUserId());
		List<Map<String, Object>> users = this.userMapper.selectUser(user);
		if(CollectionUtils.isEmpty(users)) {
			throw new BusinessException("导出失败，查询用户信息失败");
		}

		realtyEarnings.setDates(dates);
		realtyEarnings.setState("2");		//已入账
//		List<Map<String, Object>> earnings = realtyEarningsMapper.countMonthEarnings(realtyEarnings);

		File exportFile = createEarningsDetailFile(realtys, realtyEarnings, users.get(0));

		String exportPdfFilePath = StringUtils.replace(exportFile.getAbsolutePath(), ".xlsx", ".pdf");
		String licensePath = Const.DIR_UPLOAD_BASE+"/export/license.xml";

		int[] sheets = new int[realtys.size()];
		for (int i = 0; i < sheets.length; i++) {
			sheets[i] = i;
		}

		Excel2PDF.excel2pdf(exportFile.getAbsolutePath(), exportPdfFilePath, licensePath, sheets);

		File exportPdfFile = new File(exportPdfFilePath);

//		return downloadFile(exportPdfFile);

		return Const.FILE_HOST_URL + "/export/" + exportPdfFile.getName();
	}

	/**
	 * 生成收益详情文件
	 * @return
	 */
	private File createEarningsDetailFile(List<Map<String, Object>> realtys, RealtyEarnings realtyEarnings, Map<String, Object> userInfoMap) {
		FileInputStream fis = null;
		XSSFWorkbook wb = null;
		try {
			String title = createTitleName(realtyEarnings);

			String templateExcelPath = getTemplatePath(realtyEarnings);
//			String exportExcelPath = Const.DIR_UPLOAD_BASE+"/export/"+userInfoMap.get("name")+title+"租金明细表.xlsx";
			String exportExcelPath = Const.DIR_UPLOAD_BASE+"/export/"+ UUIDGenerater.generate()+".xlsx";

			File templateExcel = new File(templateExcelPath);
			if(!templateExcel.exists()) {
				throw new BusinessException("模版文件不存在");
			}
			fis = new FileInputStream(templateExcel);
			//读取excel内容
			wb = new XSSFWorkbook(fis);
			//读取sheet
			XSSFSheet sheet = null;
			for (int i = 0; i < realtys.size(); i++) {
				if(i == 0) {
					sheet = wb.getSheetAt(0);
				} else {
					XSSFSheet srcSheet = wb.getSheetAt(0);
					sheet = wb.createSheet();
					ExcelOperationUtil.copySheet(srcSheet, sheet);
				}

				realtyEarnings.setState("2");		//已入账
				realtyEarnings.setRealtyId(realtys.get(i).get("id").toString());
				List<Map<String, Object>> earnings = realtyEarningsMapper.selectRealtyEarnings(realtyEarnings);

				//设置客户名称
				sheet.getRow(6).getCell(3).setCellValue(title+"租金");
				sheet.getRow(7).getCell(3).setCellValue(userInfoMap.get("name").toString());
//				sheet.getRow(8).getCell(3).setCellValue(realtys.get(i).get("buildingAddress").toString());
				sheet.getRow(8).getCell(3).setCellValue(realtys.get(i).get("buildingName").toString()
						+" "+  realtys.get(i).get("roomNum").toString());

				setExcelDetail(realtyEarnings,earnings,sheet,title);		//设置详情
				wb.setSheetName(i, i+realtys.get(i).get("buildingName").toString()+"租金");
			}

			File exportExcel = new File(exportExcelPath);
			if(exportExcel.exists()) {
				exportExcel.delete();
			}
			exportExcel.createNewFile();

			wb.write(new FileOutputStream(exportExcel));
			wb.close();
			fis.close();

			return exportExcel;
		} catch (Exception e) {
			throw new BusinessException(String.format("生成excel失败, 失败原因[%s]", e.getMessage()));
		} finally {
			if(wb != null) {
				try {
					wb.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 *      设置详情
	 * @param realtyEarnings
	 * @param realtyInfoMap
	 * @param earnings
	 * @param sheet
	 * @param title
	 */
	private void setExcelDetail(RealtyEarnings realtyEarnings, List<Map<String, Object>> earnings, XSSFSheet sheet, String title) {
		Map<String, Map<String, Object>> earningsMap = earningsToMap(earnings);
		String date;
		int rowIndex = 11;
		Map<String, Object> earning;
		BigDecimal totalIncomeCost = new BigDecimal(0);

		for (int i = 0; i < realtyEarnings.getDates().size(); i++) {
			date = realtyEarnings.getDates().get(i);
			earning = earningsMap.get(date);
			sheet.getRow(++rowIndex).getCell(1).setCellValue(StringUtils.replace(date, "-", "/"));
			sheet.getRow(rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("rent").toString()).add(new BigDecimal(earning.get("leaseManageCost").toString())))));
			sheet.getRow(++rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("manageCost").toString()).add(new BigDecimal(earning.get("fixCost").toString())))));
			sheet.getRow(++rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("serviceCost").toString()))));
			sheet.getRow(++rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("agencyCost").toString()))));
			sheet.getRow(++rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("dayCost").toString()))));
			sheet.getRow(++rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("eqFixCost").toString()))));
			sheet.getRow(++rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("taxesCost").toString()))));
			sheet.getRow(++rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("otherCost").toString()))));
			sheet.getRow(++rowIndex).getCell(5).setCellValue(Double.parseDouble(""+(earning==null?0:new BigDecimal(earning.get("incomeCost").toString()))));

			totalIncomeCost = totalIncomeCost.add((earning==null?new BigDecimal(0):new BigDecimal(earning.get("incomeCost").toString())));

			if(i+1 < realtyEarnings.getDates().size()) {
				rowIndex ++;
			}
		}

		rowIndex += 2;
		sheet.getRow(rowIndex).getCell(3).setCellValue(title + " 淨收入總收入");
		sheet.getRow(rowIndex).getCell(5).setCellValue(Double.parseDouble(""+totalIncomeCost));
	}
	private Map<String, Map<String, Object>> earningsToMap(List<Map<String, Object>> earnings) {
		Map<String, Map<String, Object>> result = new HashMap<>();
		for (Map<String, Object> earning : earnings) {
			result.put(earning.get("accountDate").toString(), earning);
		}

		return result;
	}

	private String getTemplatePath(RealtyEarnings realtyEarnings) {
		String templatepath = Const.DIR_UPLOAD_BASE+Const.EXCEL_EARNING_TEMPLETE;

		switch (realtyEarnings.getExportType()) {
			//年
			case "1":
				templatepath += "_Y.xlsx";
				break;
			//月
			case "2":
				templatepath += "_M.xlsx";
				break;
			//季度
			case "3":
				templatepath += "_J.xlsx";
				break;
		}

		return templatepath;
	}

	/**
	 * 创建title
	 * @param realtyEarnings
	 * @return
	 */
	private String createTitleName(RealtyEarnings realtyEarnings) {
		String titleName = null;
		Calendar now = Calendar.getInstance();
		String year = String.valueOf(now.get(Calendar.YEAR));

		switch (realtyEarnings.getExportType()) {
			//年
			case "1":
				titleName = String.format("%s年度", realtyEarnings.getExportVaule());
				break;
			//月
			case "2":
				titleName = String.format("%s年%02d月份", year, Integer.parseInt(realtyEarnings.getExportVaule()));
				break;
			//季度
			case "3":
				titleName = String.format("%s年%02d月至%02d月", year, Integer.parseInt(realtyEarnings.getExportVaule())*3-2, Integer.parseInt(realtyEarnings.getExportVaule())*3);
				break;
		}

		return titleName;
	}

	/**
	 * 创建查询时间
	 * @param realtyEarnings
	 * @return
	 */
	private ArrayList createDates(RealtyEarnings realtyEarnings) {
		ArrayList<String> dates = null;

		Calendar now = Calendar.getInstance();
		String year = String.valueOf(now.get(Calendar.YEAR));

		switch (realtyEarnings.getExportType()) {
			//年
			case "1":
				dates = createDates(realtyEarnings.getExportVaule(), 1, 12);
				break;
			//月
			case "2":
				dates = createDates(year, Integer.parseInt(realtyEarnings.getExportVaule()), Integer.parseInt(realtyEarnings.getExportVaule()));
				break;
			//季度
			case "3":
				dates = createDates(year, Integer.parseInt(realtyEarnings.getExportVaule())*3-2, Integer.parseInt(realtyEarnings.getExportVaule())*3);
				break;
		}

		return dates;
	}

	/**
	 * 创建月份数组
	 * @param year
	 * @param start
	 * @param end
	 * @return
	 */
	private ArrayList createDates(String year, int start, int end) {
		ArrayList<String> dates = new ArrayList<>();
		for (int i=start; i<=end; i ++) {
			dates.add(year+"-"+String.format("%02d", i));
		}

		return dates;
	}

	/**
	 * @param file
	 * @return
	 * @throws IOException
	 * @Description 下载文件
	 */
	public ResponseEntity<byte[]> downloadFile(File file) throws IOException {
		String fileName = new String(file.getName().getBytes("gb2312"), "iso8859-1");
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", fileName);
		ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);

//		file.delete();          //删除导出的文件
		return responseEntity;
	}

	/**
	 * 设置客户总资产
	 * @param data
	 * @param realtyEarnings
	 */
	private void setBuyPrice(Map<String, BigDecimal> data, RealtyEarnings realtyEarnings) {
		//获取客户总资产
		RealtyInfo realtyInfo = new RealtyInfo();
		realtyInfo.setRate(realtyEarnings.getRate());
		realtyInfo.setCustomerId(SecurityContext.getUserId());
		Map<String, Object> assetInfo = realtyInfoMapper.countCustomerAsset(realtyInfo);
		if(assetInfo == null) {
			return;
		}

		BigDecimal totalBuyPrice = new BigDecimal(assetInfo.get("asset")==null?"0":assetInfo.get("asset").toString());
		BigDecimal totalBuyJPrice = new BigDecimal(assetInfo.get("JAsset")==null?"0":assetInfo.get("JAsset").toString());
		totalBuyPrice = totalBuyPrice.multiply(new BigDecimal(10000));
		totalBuyJPrice = totalBuyJPrice.multiply(new BigDecimal(10000));

		data.put("totalBuyPrice", totalBuyPrice.setScale(2,BigDecimal.ROUND_HALF_UP));
		data.put("totalBuyJPrice", totalBuyJPrice.setScale(2,BigDecimal.ROUND_HALF_UP));
	}

	/**
	 * 设置客户累计现金流
	 * @param data
	 * @param realtyEarnings
	 */
	private void setCustomerTotalMoney(Map<String, BigDecimal> data, RealtyEarnings realtyEarnings) {
		RealtyEarnings earnings = new RealtyEarnings();
		earnings.setCustomerId(SecurityContext.getUserId());
		earnings.setRate(realtyEarnings.getRate());
		Map<String, Object> totalMoneyData = this.realtyEarningsMapper.countTotalMoney(earnings);
		if(totalMoneyData == null) {
			return;
		}
		BigDecimal totalMoney = new BigDecimal(totalMoneyData.get("totalMoney")==null?"0":totalMoneyData.get("totalMoney").toString());
		BigDecimal totalJMoney = new BigDecimal(totalMoneyData.get("totalJMoney")==null?"0":totalMoneyData.get("totalJMoney").toString());

		data.put("totalMoney", totalMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
		data.put("totalJMoney", totalJMoney.setScale(2,BigDecimal.ROUND_HALF_UP));
	}

	/**
	 *       设置客户总支出
	 * @param data
	 * @param realtyEarnings
	 */
	private void setCustomerZZC(Map<String, BigDecimal> data, RealtyEarnings realtyEarnings) {
		//获取客户年份统计结果
		Map<String, Object> yearData = this.realtyEarningsMapper.countYearEarnings(realtyEarnings);
		if(yearData == null) {
			return ;
		}
		BigDecimal totalZZC = new BigDecimal(yearData.get("zzc")==null?"0":yearData.get("zzc").toString());
		BigDecimal totalJZZC = new BigDecimal(yearData.get("Jzzc")==null?"0":yearData.get("Jzzc").toString());
		data.put("totalZZC", totalZZC.setScale(2,BigDecimal.ROUND_HALF_UP));
		data.put("totalJZZC", totalJZZC.setScale(2,BigDecimal.ROUND_HALF_UP));
	}

	/**
	 *       设置客户总支出
	 * @param data
	 * @param realtyEarnings
	 */
	private void setCustomerZZCByZnl(Map<String, BigDecimal> data, RealtyEarnings realtyEarnings) {
		//获取客户年份统计结果
		realtyEarnings.setYears("2020");
		Map<String, Object> yearData = this.realtyEarningsMapper.countYearEarningsForZnl(realtyEarnings);
		if(yearData == null) {
			return ;
		}
		BigDecimal totalZZC = new BigDecimal(yearData.get("zzc")==null?"0":yearData.get("zzc").toString());
		BigDecimal totalJZZC = new BigDecimal(yearData.get("Jzzc")==null?"0":yearData.get("Jzzc").toString());
		data.put("totalZZCForZnl", totalZZC.setScale(2,BigDecimal.ROUND_HALF_UP));
		data.put("totalJZZCForZnl", totalJZZC.setScale(2,BigDecimal.ROUND_HALF_UP));
	}

	/**
	 * 设置客户汇款总额
	 * @param data
	 * @param realtyEarnings
	 */
	private void setCustomerReceipts(Map<String, BigDecimal> data, RealtyEarnings realtyEarnings) throws Exception {
		//获取客户汇款总额
		Receipts receipts = new Receipts();
		receipts.setCustomerId(realtyEarnings.getCustomerId());
		if(StringUtils.isBlank(realtyEarnings.getMoneyTypeCode())) {
			receipts.setMoneyType("JPY");
		} else {
			receipts.setMoneyType(realtyEarnings.getMoneyTypeCode());
		}
		receipts.setPaymentYear(realtyEarnings.getAccountDate());
		receipts.setStatus("1");
		Map<String, Object> receiptsData = iReceiptsService.queryReceiptsTotalNoFormat(receipts);
		if(receiptsData == null) {
			return;
		}

		NumberFormat format = NumberFormat.getInstance();

		BigDecimal totalReceipts = new BigDecimal(receiptsData.get("targetTotal")==null?"0":format.parse(receiptsData.get("targetTotal").toString()).toString());
		BigDecimal totalJReceipts = new BigDecimal(receiptsData.get("total")==null?"0":receiptsData.get("total").toString());
		data.put("totalReceipts", totalReceipts.setScale(2,BigDecimal.ROUND_HALF_UP));
		data.put("totalJReceipts", totalJReceipts.setScale(2,BigDecimal.ROUND_HALF_UP));
	}

	/**
	 *  获取汇率
	 * @param realtyEarnings
	 * @return
	 */
	private BigDecimal getRate(RealtyEarnings realtyEarnings) {
		BigDecimal rate = null;
		if(!StringUtils.isBlank(realtyEarnings.getMoneyTypeCode()) && !StringUtils.equals(realtyEarnings.getMoneyTypeCode(), "JPY")) {
			Map<String, Object> rateMap = rateService.queryMoenyRate(realtyEarnings.getMoneyTypeCode());
			if(rateMap != null) {
				if(rateMap.get("rate") != null) {
					rate = (BigDecimal) rateMap.get("rate");
					realtyEarnings.setRate(rate);
				}
			}
		} else {
			rate = new BigDecimal(1);
			realtyEarnings.setRate(rate);
		}

		if(rate == null) {
			return null;
		}

		return rate;
	}
}
